<template>
	<el-container class="friend-page">
		<el-aside  class="friend-list-box" :style="{ width: scrollbarWidth + 'px' }">
			<div class="friend-list-header" style="">
				<el-input class="search-text" size="small" placeholder="搜索" v-model="searchText" style="">
					<i class="el-icon-search el-input__icon" slot="prefix"> </i>
				</el-input>
				<el-button plain class="add-btn" icon="el-icon-plus" title="添加好友" style=""
					@click="onShowAddFriend()"></el-button>
				<add-friend :dialogVisible="showAddFriend" @close="onCloseAddFriend"></add-friend>
			</div>
			<!-- xiugai- -->
			<el-scrollbar class="friend-list-items">
				<div class="friend-item" @click="checkNewFriends">
					<div>{{ $t('新的朋友') }}
						<div v-show="newFriends > 0" class="unread-text">{{ newFriends }}</div>
					</div>
				</div>
				<div v-for="(friend, index) in $store.state.friendStore.friends" :key="index">
					<friend-item v-show="friend.nickname.includes(searchText)" :index="index"
						:active="friend === $store.state.friendStore.activeFriend" @chat="onSendMessage(friend)"
						@delete="onDelItem(friend, index)" @click.native="onActiveItem(friend, index)">
					</friend-item>
				</div>
			</el-scrollbar>
       <div class="resizer" @mousedown.stop.prevent="onMouseDown"></div>

		</el-aside>
		<el-container class="friend-box">
			<!-- 空数据 -->
			<div class="drag-box-null" v-show="!userInfo.id && pageType != 'newFriends'">
				<dragBar></dragBar>
			</div>

			<!-- 添加好友列表 -->
			<div class="drag-box-null newFriends" v-show="pageType == 'newFriends'">
				<div class="friend-header drag-box ">
					<div>新的朋友</div>
					<dragBar></dragBar>
				</div>
			</div>

			<div v-show="pageType == 'newFriends'" class="new-friends-box drag-box-none">
				<div class="friend-list">
					<div class="friend-item" v-for="(friend, index) in friendList" :key="index"
						@click.stop="showFriendInfo()">
						<head-image :size="50" :name="friend.nickname" :url="friend.avatarThumb"
							@click.native="showFullImage()"></head-image>
						<div class="friend-info">
							<div class="friend-name">{{ friend.nickname }}</div>
							<div v-if="friend.status == 1" class="btn" @click="updateFriendFn(friend)">
								{{ $t('通过验证') }}</div>
							<div v-if="friend.status == 2" class="rightText">已同意</div>
							<div v-if="friend.status == 3" class="rightText">>已过期</div>
						</div>
					</div>
				</div>
			</div>

			<!-- 朋友 -->
			<div class="friend-header drag-box" v-show="userInfo.id && pageType == 'friend'">
				{{ userInfo.nickname }}
				<dragBar></dragBar>
			</div>

			<div v-show="userInfo.id && pageType == 'friend'" class="drag-box-none">
				<div class="friend-detail">
					<head-image :size="160" :name="userInfo.nickname" :url="userInfo.avatarThumb"
						@click.native="showFullImage()"></head-image>
					<div>
						<div class="info-item">
							<el-descriptions :title="userInfo.nickname" class="description" :column="1">
								<el-descriptions-item :label="$t('ID')">{{ userInfo.id }}
								</el-descriptions-item>
								<el-descriptions-item :label="$t('用户名')">{{ userInfo.account }}
									<el-tag v-if="userInfo.status == 1" size="mini" type="danger">已注销</el-tag>
								</el-descriptions-item>
								<!-- <el-descriptions-item :label="$t('昵称')">{{ userInfo.nickname }}
								</el-descriptions-item> -->
								<el-descriptions-item :label="$t('性别')">{{ userInfo.sex == 0 ? $t('男') : $t('女')
								}}</el-descriptions-item>
								<el-descriptions-item :label="$t('签名')">{{ userInfo.signature }}</el-descriptions-item>
							</el-descriptions>
						</div>
						<div class="frient-btn-group">
							<el-button v-show="userInfo.isFriend" icon="el-icon-position" type="primary"
								@click="onSendMessage(userInfo)">{{ $t('发消息') }}</el-button>
							<el-button icon="el-icon-edit" @click="onEditName(userInfo)">{{ $t('修改备注') }}</el-button>
							<el-button v-show="!userInfo.isFriend" icon="el-icon-plus" type="primary"
								@click="onAddFriend(userInfo)">{{ $t('加为好友') }}</el-button>
							<el-button v-show="userInfo.isFriend" icon="el-icon-delete" type="danger"
								@click="onDelItem(userInfo, activeIdx)">{{ $t('删除好友') }}</el-button>
						</div>
					</div>
				</div>
				<!--				<el-divider content-position="center"></el-divider>-->

			</div>
		</el-container>
	</el-container>
</template>

<script>
import FriendItem from "../components/friend/FriendItem.vue";
import AddFriend from "../components/friend/AddFriend.vue";
import HeadImage from "../components/common/HeadImage.vue";
import dragBar from '@/view/components/dragBar'


export default {
	name: "friend",
	components: {
		FriendItem,
		AddFriend,
		HeadImage,
		dragBar
	},
	data() {
		return {
			pageType: '',
			searchText: "",
			showAddFriend: false,
			activeIdx: -1,
			userInfo: {},
			friendList: [],
      		isDragging: false,

		}
	},
	methods: {
		onMouseDown(event) {
      this.isDragging = true;
      const startX = event.clientX;
      
      const startWidth = this.scrollbarWidth;

      const doDrag = (e) => {
        if (this.isDragging) {
          let scrollWidth = startWidth + (e.clientX - startX);
          // this.scrollbarWidth = scrollWidth
          this.$store.commit("setWidthData", scrollWidth);
      }
      };
      const stopDrag = () => {
        this.isDragging = false;
        document.removeEventListener("mousemove", doDrag);
        document.removeEventListener("mouseup", stopDrag);
      };

      document.addEventListener("mousemove", doDrag);
      document.addEventListener("mouseup", stopDrag);
    },
		sendSocketMessage(user) {
			const timestamp = new Date().getTime();
			let socketMessage = {
				atUserIds: [],
				content: this.$t("请求添加好友"),
				id: 0,
				receipt: false,
				recvId: user.id,
				selfSend: true,
				sendId: this.$store.state.userStore.userInfo.id,
				sendTime: timestamp,
				status: 0,
				type: 7
			}

			this.$http({
				url: `/im/message/private/send`,
				method: 'post',
				data: socketMessage
			})
		},
		sendAddFriendsMessage(user) {
			let chat = {
				type: 'PRIVATE',
				targetId: user.id,
				showName: user.nickname,
				headImage: user.avatar,
				avatar: user.avatar,
				avatarThumb: user.avatarThumb,
				sendTime: new Date().getTime(),
				selfSend: true
			};
			this.$store.commit("openChat", chat);
			this.$store.commit("activeChat", 0);

			let msgInfo = {
				content: this.$t('请求添加好友'),
				type: 0,
				recvId: user.id,
			}

			this.$http({
				url: `/im/message/private/send`,
				method: 'post',
				data: msgInfo
			}).then((res) => {
				res.selfSend = true
				this.$store.commit("insertMessage", [res, chat]);
			})
		},
		sendFriendMessage(user) {
			console.log(user)
			let chat = {
				type: 'PRIVATE',
				targetId: user.friendId,
				showName: user.nickname,
				headImage: user.avatar,
				avatar: user.avatar,
				avatarThumb: user.avatarThumb,
				sendTime: new Date().getTime(),
				selfSend: true

			};
			console.log(chat.targetId)
			this.$store.commit("openChat", chat);
			this.$store.commit("activeChat", 0);

			let msgInfo = {
				content: this.$t('我已经是你的好友啦'),
				type: 0,
				recvId: user.friendId,
			}


			this.$http({
				url: `/im/message/private/send`,
				method: 'post',
				data: msgInfo
			}).then((res) => {
				res.selfSend = true
				this.$store.commit("insertMessage", [res, chat]);
			})
		},
		updateFriendFn(friend) {
			let obj = {
				id: friend.id,
				status: 2
			}

			this.$http({
				url: `/friendapply/update`,
				method: 'post',
				data: obj
			}).then((data) => {
				this.$message.success("操作成功");
				// 列表修改状态
				console.log(this.friendList)
				let updateFriend = this.friendList.find(item => item.id == obj.id);
				updateFriend.status = 2
				console.log(updateFriend)
				this.sendFriendMessage(updateFriend)
			})
		},
		showFriendInfo() { },
		checkNewFriends() {
			this.$store.dispatch('clearFriendsMessage')
			this.$http({
				url: `/friendapply/list`,
				method: 'get'
			}).then((data) => {
				let list = data.list;
				list.forEach(e => {
					if (e.senderId == this.$store.state.userStore.userInfo.id) {
						e.avatarThumb = e.receiverAvatarThumb,
							e.avatar = e.receiverAvatar,
							e.nickname = e.receiverNickName
						e.friendId = e.receiverId
						// e.id = e.receiverId
					} else {
						e.avatarThumb = e.senderAvatarThumb,
							e.avatar = e.senderAvatar,
							e.nickname = e.senderNickName
						e.friendId = e.senderId
						// e.id = e.senderId
					}
				})
				this.friendList = list.sort((a, b) => {
					b.id - a.id
				})
			})

			this.pageType = 'newFriends'
		},
		onShowAddFriend() {
			this.showAddFriend = true;
		},
		onCloseAddFriend() {
			this.showAddFriend = false;
		},
		onActiveItem(friend, idx) {
			this.$store.commit("activeFriend", idx);
			this.activeIdx = idx
			this.loadUserInfo(friend, idx);
			this.pageType = 'friend'
		},
		onEditName(friend, idx) {
			this.$prompt(`请输入修改备注名`, {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(({ value }) => {
				let parameters = {
					nickname: value,
					id: this.userInfo.id
				}
				this.$http({
					url: `/im/friend/update`,
					data: parameters,
					method: 'put'
				}).then((data) => {
					this.$message.success("修改成功");
					this.userInfo.nickname = value;
					this.$store.commit("updateChatFromFriend", this.userInfo);
					this.$store.commit("updateFriend", this.userInfo);
				})
			})
		},
		onDelItem(friend, idx) {
			this.$confirm(`确认删除'${friend.nickname}',并清空聊天记录吗?`, '确认解除?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$http({
					url: `/im/friend/delete/${friend.id}`,
					method: 'delete'
				}).then((data) => {
					this.$message.success("删除好友成功");
					this.$store.commit("removeFriend", idx);
					this.$store.commit("removePrivateChat", friend.id);
					this.userInfo = {}
				})
			})
		},
		onAddFriend(user) {
			this.$http({
				url: "/im/friend/add",
				method: "post",
				params: {
					friendId: user.id
				}
			}).then((data) => {
				this.sendSocketMessage(user)

				if (user.friendAddRestrict == 1) {
					this.$message.success("申请成功,等待对方同意");
				} else {
					this.$message.success("添加成功，对方已成为您的好友");
					let friend = {
						id: user.id,
						nickname: user.nickname,
						headImage: user.headImage,
						avatar: user.avatar,
						avatarThumb: user.avatarThumb,
						online: user.online
					}
					this.$store.commit("addFriend", friend);
					this.userInfo.isFriend = true
					this.sendAddFriendsMessage(user);
				}
			})
		},
		onSendMessage(user) {
			let chat = {
				type: 'PRIVATE',
				targetId: user.id,
				showName: user.nickname,
				headImage: user.avatar,
				avatarThumb: user.avatarThumb,
				avatar: user.avatar
			};
			this.$store.commit("openChat", chat);
			this.$store.commit("activeChat", 0);
			this.$router.push("/home/chat");
		},
		showFullImage() {
			if (this.userInfo.avatar) {
				this.$store.commit('showFullImageBox', this.userInfo.avatar);
			}
		},
		updateFriendInfo(friend, user, index) {
			// store的数据不能直接修改，深拷贝一份store的数据
			friend = JSON.parse(JSON.stringify(friend));
			friend.headImage = user.avatarThumb;
			friend.avatar = user.avatar;
			friend.avatarThumb = user.avatarThumb;
			friend.nickname = user.nickname;
			this.$http({
				url: "/im/friend/update",
				method: "put",
				data: friend
			}).then(() => {
				this.$store.commit("updateFriend", friend);
				this.$store.commit("updateChatFromFriend", user);
			})
		},
		loadUserInfo(friend, index) {
			this.$http({
				url: `/im/friend/find/${friend.id}`,
				method: 'get'
			}).then((user) => {
				this.userInfo = user;
				// 如果发现好友的头像和昵称改了，进行更新
				if (user.avatarThumb != friend.avatarThumb ||
					user.nickname != friend.nickname) {
					this.updateFriendInfo(friend, user, index)
				}
			})
		}
	},
	computed: {
		newFriends() {
			return this.$store.state.friendStore.newFriends;
		},
		friendStore() {
			return this.$store.state.friendStore;
		},
		scrollbarWidth() {
      		return this.$store.state.chatStore.scrollbarWidthData ||260;
    },
	}
}
</script>

<style lang="scss" scoped>
.scrollbar-container {
  display: flex;
  align-items: stretch;
}
.resizer {
  width: 10px; /* 可调整的宽度 */
  cursor: ew-resize;
      position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    background: #eee;
    z-index: 999;
}
.unread-text {
	position: absolute;
	background-color: var(--im-color-danger);
	right: 20px;
	top: 18px;
	color: white;
	border-radius: 30px;
	padding: 0 5px;
	font-size: var(--im-font-size-smaller);
	text-align: center;
	white-space: nowrap;
	border: 1px solid #f1e5e5;
}

.friend-list {
	display: flex;
	flex-direction: column;
	padding: 30px 50px;

	.friend-item {
		display: flex;
		// margin-bottom: 30px;
		height: 70px;
		border-bottom: 1px solid #e2e2e2;

		.friend-info {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;

			.btn {
				background-color: #255F46;
				color: #fff;
				padding: 8px 15px;
				border-radius: 5px;
			}
		}
	}
}

.friend-page {
	.friend-list-box {
		display: flex;
		flex-direction: column;
		background: var(--im-background);
  min-width: 240px;
    max-width: 500px;
	    position: relative;
		.friend-list-header {
			height: 50px;
			display: flex;
			align-items: center;
			padding: 0 8px;

			.add-btn {
				padding: 5px !important;
				margin: 5px;
				font-size: 16px;
				border-radius: 50%;
			}
		}

		.friend-list-items {
			flex: 1;
		}
	}

	.friend-box {
		display: flex;
		flex-direction: column;

		.new-friends-box {
			flex-grow: 1;
			height: 100%;
			overflow: auto;
		}

		.friend-header {
			height: 50px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 12px;
			font-size: var(--im-font-size-larger);
			border-bottom: var(--im-border);
			box-sizing: border-box;
		}

		.friend-detail {
			display: flex;
			padding: 50px 80px 20px 80px;
			text-align: center;


			.info-item {
				margin-left: 20px;
				background-color: #ffffff;
				border: 1px #ddd solid;
			}

			.description {
				padding: 20px 20px 0 20px;
			}
		}

		.frient-btn-group {
			text-align: left !important;
			padding: 20px;
		}
	}
}
</style>
